package com.svms.save.services;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.svms.save.config.SvmsSaveConfig;
import com.svms.save.utils.CommonUtils;
import com.svms.save.utils.DateUtils;
import com.svms.save.utils.EncryptUtil;
import com.svms.save.utils.NetworkUtil;
import com.svms.save.utils.SysCode;
import com.svms.save.vo.LicenseVo;
import com.svms.save.vo.ResultVo;

public abstract class LicenseService {
	@Autowired
	private SvmsSaveConfig config;
	
	public static final String ERRMSG_LICENSE_FILE = "授权文件异常！";
	public static final String ERRMSG_LICENSE_FILE_NOT_FONT = "读取授权文件异常，请输入授权码！";
	public static final String ERRMSG_LICENSE_MAC_ERROR = "该授权码与服务器不符！";
	public static final String ERRMSG_LICENSE_ERROR = "您输入的授权码不正确！";
	public static final String ERRMSG_LICENSE_SDATE = "服务器时间异常！";
	public static final String ERRMSG_LICENSE_EDATE = "授权已过期！";
	
	private Logger log = LoggerFactory.getLogger(LicenseService.class);
	/**
	 * 获取当前授权信息
	 * @return
	 */
	public LicenseVo getThisLicense(String licenStr) {
		LicenseVo licen = new LicenseVo();
		licen.setVersion(config.getSystemVersion());
		EncryptUtil encrypt = EncryptUtil.getInstance();
		if(null == licenStr) {
			licenStr = this.readLicenseFile();
		}
		try {
			if(StringUtils.isNotBlank(licenStr)) {
				String licenJson = encrypt.AESdecode(licenStr, SysCode.KEY);
				if(StringUtils.isNotBlank(licenJson)) {
					JSONObject json = JSONObject.parseObject(licenJson);
					licen = JSONObject.toJavaObject(json, LicenseVo.class);
				}else {
					String msg = String.format("授权码不正确【%s】！", licenStr);
					licen.setErrMsg(ERRMSG_LICENSE_ERROR);
					log.error(msg);
				}
			}else {
				licen.setErrMsg(ERRMSG_LICENSE_FILE_NOT_FONT);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			String msg = "解析license文件错误！";
			licen.setErrMsg(ERRMSG_LICENSE_ERROR);
			log.error(msg,e);
		}
		return licen;
	}

	private String readLicenseFile() {
		StringBuffer sbf = new StringBuffer();
		try {
			File file = ResourceUtils.getFile(getLicenseFile());
			if(file.exists()) {
				BufferedReader reader = null;
				InputStreamReader isr = null;
				try {
					isr = new InputStreamReader(new FileInputStream(file), SysCode.DEF_CHARSET);
					reader = new BufferedReader(isr);
					String tempStr;
					while ((tempStr = reader.readLine()) != null) {
					    sbf.append(tempStr);
					}
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					log.error("读取license文件错误！",e);
				}finally {
					try {
						if(null != isr) {
							isr.close();
						}
						if(null != reader) {
							reader.close();
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						log.error("读取license文件错误！",e);
					}
				}
			}else {
				log.error(String.format("授权文件【%s】不存在！", config.getLicensePath()));
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			log.error("获取license文件错误！",e);
		}
		return sbf.toString();
	}
	
	public LicenseVo validateLicense(boolean testMAC) {
		LicenseVo licen = validateLicense(null,testMAC);
		return licen;
	}
	public LicenseVo validateLicense(LicenseVo licen,boolean testMAC) {
		if(null == licen) {
			licen = getThisLicense(null);
		}
		String start = licen.getStartDate();
		String end = licen.getEndDate();
		List<String> mac = licen.getMacList();
		if(ResultVo.SUCCESSS.equals(licen.getState())) {
			if(testMAC) {
				if(!this.validateMac(mac)) {
					licen.setErrMsg(ERRMSG_LICENSE_MAC_ERROR);
				}
			}
			if(!this.validateStartDate(start)) {
				licen.setErrMsg(ERRMSG_LICENSE_SDATE);
			}
			if(!this.validateEndDate(end)) {
				licen.setErrMsg(ERRMSG_LICENSE_EDATE);
			}
		}
		return licen;
	}
	/**
	 * mac地址验证
	 * @param mac
	 * @return
	 */
	public boolean validateMac(List<String> mac) {
		boolean flag = false;
		if(null != mac && !mac.isEmpty()) {
			Set<NetworkInterface> nicSet = NetworkUtil.getPhysicalNICs();
			Iterator<NetworkInterface> nicIt = nicSet.iterator();
			while(nicIt.hasNext()) {
				NetworkInterface nic = nicIt.next();
				String thisMac = NetworkUtil.getMacAddress(nic, SysCode.MAC_SEPARATOR);
				for(String _mac : mac) {
					if(thisMac.equals(_mac)) {
						flag = true;
						return flag;
					}
				}
			}
		}
		return flag;
	}
	/**
	 * 起始时间与系统时间比较验证
	 * @param start
	 * @return
	 */
	public boolean validateStartDate(String start) {
		boolean flag = false;
		if(StringUtils.isNotBlank(start)) {
			Date startD = DateUtils.strTdate(start);
			Date nowDate = new Date();
			if(nowDate.getTime() >= startD.getTime()) {
				flag = true;
				return flag;
			}
		}
		return flag;
	}
	/**
	 * 截止日期验证
	 * @param end
	 * @return
	 */
	public boolean validateEndDate(String end) {
		boolean flag = false;
		if(StringUtils.isNotBlank(end)) {
			Date endD = DateUtils.strTdate(end);
			Date nowDate = new Date();
			if(endD.getTime() >= nowDate.getTime()) {
				flag = true;
				return flag;
			}
		}
		return flag;
	}
	/**
	 * 写入有效的授权码
	 * @param licenseStr 授权许可字符串
	 * @return
	 */
	public LicenseVo writeLicense(String licenseStr) {
		PrintWriter pw = null;
		LicenseVo licen = this.getThisLicense(licenseStr);
		licen = this.validateLicense(licen, true);
		if(ResultVo.SUCCESSS.equals(licen.getState())) {
			try {
				File file = ResourceUtils.getFile(config.getLicensePath());
				File licenseFile = ResourceUtils.getFile(getLicenseFile());
				if(!file.exists()) {
					file.mkdirs();
					licenseFile.createNewFile();
				}
				pw = new PrintWriter(licenseFile);
				pw.write(licenseStr);
				pw.flush();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				log.error("系统错误！",e);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.error("系统错误！",e);
			}finally {
				if(null != pw) {
					pw.close();
				}
			}
		}
		return licen;
	}
	/**
	 * 获取授权码
	 * @return
	 */
	public String getLicenseKey() {
		List<String> macList = new ArrayList<String>();
		Set<NetworkInterface> nicSet = NetworkUtil.getPhysicalNICs();
		Iterator<NetworkInterface> nicIt = nicSet.iterator();
		while(nicIt.hasNext()) {
			NetworkInterface nic = nicIt.next();
			String thisMac = NetworkUtil.getMacAddress(nic, SysCode.MAC_SEPARATOR);
			macList.add(thisMac);
		}
		String licenKey = JSONArray.toJSONString(macList);
		EncryptUtil encrypt = EncryptUtil.getInstance();
		String licenCode = encrypt.AESencode(licenKey, SysCode.KEY);
		return licenCode;
	}
	
	public String getLicenseFile() {
		return config.getLicensePath()+SysCode.LICENSE;
	}
}
